<?php

namespace addons\venue\controller;

use addons\epay\library\Service;
use app\admin\model\venue\activity\Activity as Av;
use app\admin\model\venue\activity\UserActivity;
use app\admin\model\venue\area\Rule;
use app\admin\model\venue\coupon\Receive;
use app\admin\model\venue\Detail;
use app\admin\model\venue\lesson\UserLesson;
use app\admin\model\venue\message\Message;
use app\admin\model\venue\user\Balance;
use app\admin\model\venue\user\Store;
use app\admin\model\venue\venue\Relationship;
use app\admin\model\venue\venue\Reserve;
use app\admin\model\venue\venue\Type;
use app\common\controller\Api;
use app\admin\model\venue\goods\Goods;
use app\admin\model\venue\Coupon;
use app\admin\model\venue\order\Order as Od;
use app\common\model\venue\activity\Cc;
use app\common\model\venue\Recharge;
use think\Db;
use app\admin\model\venue\venue\Venue;
use app\admin\model\venue\lesson\Lesson;
use think\Log;
use think\Queue;
use think\Cache;
use app\admin\model\venue\order\Refund;
use think\Request;
use Yansongda\Pay\Pay;


class Order extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['notifyx','recharge'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    protected $config = "";

    public function __construct(Request $request = null)
    {
        $this->config = get_addon_config("venue");
        parent::__construct($request);
    }

    /*
     * 充值优惠列表
     */
    public function recharge(){
        $data = Recharge::where("status",'normal')->select();
        $this->success("成功",["data"=>$data]);
    }

    /*
     * 预申请
     */
    public function before(){
        $userId = $this->auth->id;
        $data = $this->request->post();
        $orderType   = $data['orderType']??1;        // 订单类型 1积分订单 2商品订单 3课程订单 4活动订单
        $hd_cc_id   = $data['hd_cc_id']??0;        // 活动场次id
        $goodsId     = $data['goodsId']??0;          // 商品ID
        $goodsCount  = $data['goodsCount']??1;       // 商品数量
        $areaDetail  = $data['areaDetail']??[];      // 选择的场次信息
        $fixedDate   = $data['fixedDate']??"";       // 预定日期
        $couponId    = $data['couponId']??0;         // 优惠券ID
        $lessonType  = $data['lessonType']??"周卡";   // 课程次数类型
        if (!$goodsId){
            $this->error("缺少商品id");
        }
        if (!$orderType){
            $this->error("缺少订单类型");
        }
        //计算实际付款金额
        if ($orderType == 1){
            $goods = Goods::where("id",$goodsId)->field("id,title,price,stock,daily")->find();
            $data = [
              "selfdeliverys"=>$this->config['selfdeliverys'],
              "lx_name"=>$this->config['lx_name'],
              "lx_tel"=>$this->config['lx_tel'],
            ];
        }elseif ($orderType == 2){
            $price = 0;
            $one_price = 0;
            foreach ($areaDetail as &$v){
                if (empty($v)){
                    $this->error("请选择时间段");
                }
                $relation = Relationship::get($v['areaId']);
                $rule = $relation["rule_id"];
                $details = Rule::get($rule);
                $count = count($v['times']);
                $price = bcadd($price,bcmul($details['price'],$count,2),2);
                $one_price = bcmul($details['price'],$count);
                //获取规则

                $arr = [];
                foreach ($v['times'] as $k => $val){
                    //根据间隔时间获取开始和结束时间
                    $str_time = strtotime($fixedDate." ".$val['time']);
                    $end_time = bcadd($str_time,bcmul($details['interval_time'],3600));
                    $endTimes = date("H:i",$end_time);
                    $arr[$k]['start'] = $val['time'];
                    $arr[$k]['end'] = $endTimes;
                    $arr[$k]['price'] = $details['price'];
                    $arr[$k]['venue_name'] = $val['terminus'];
                    $arr[$k]['fixedDate'] = $val['ynd'];
                }
                $type = $relation['type_id'];
                $v['area_name'] = $relation['name'];
                $v['price'] = $one_price;
                $v['times'] = $arr;
            }
            $detail = Venue::get($goodsId);
            $data = [
                "venue_address"=>$detail['address'],
                "lon"=>$detail['lon'],
                "name"=>$detail['name'],
                "image"=>cdnurl($detail['image'],true),
                "lat"=>$detail['lat'],
                "lx_name"=>$detail['lx_name'],
                "lx_tel"=>$detail['tel'],
                "areaDetail"=>$areaDetail,
                "fixedDate"=>$fixedDate,
                "type"=>Type::where("id",$type)->value("venue_type")

            ];
            $goods['price'] = $price;
        }elseif($orderType == 3){
            $detail = Lesson::get($goodsId);
            $v_detail = Venue::get($detail['venue_id']);
            $json = json_decode($detail['details_json'],true);
            $price = 0;
            $data = [
                "venue_address"=>$v_detail['address'],
                "lon"=>$v_detail['lon'],
                "lat"=>$v_detail['lat'],
                "lx_name"=>$detail['name'],
                "lx_tel"=>$detail['tel'],
                "lesson_name"=>$detail['title'],
            ];
            foreach ($json as $v){
                if ($v['type'] == $lessonType){
                    $price = $v['price'];
                    $data['image'] = cdnurl($v['image'],true);
                    $data['type']=$v['type'];
                    $data['price']=$v['price'];
                    $data['days']=$v['days'];
                }
            }

            $goods['price'] = $price;
        }elseif($orderType == 4){
            $detail = \app\admin\model\venue\activity\Activity::get($goodsId);
            if (!$hd_cc_id){
                $this->error("缺少活动场次id");
            }
            $cc = Cc::get($hd_cc_id);
            $goods['price'] = $cc['activity_price'];
            $data = [
              "cc_title"=>$cc['title'],
              "venue"=> Venue::where("id",$detail['venue_id'])->value("name"),
              "ac_name"=> $detail['title'],
              "image"=> cdnurl($detail['image'],true),
              "type"=>Type::where("id",$detail['type_ids'])->value("venue_type"),
              "workrange"=>$detail['workrange'],
            ];
        }
        if ($couponId > 0){
            if (empty($couponId)){
                $this->error("优惠券信息有误");
            }
            //查看优惠券是否可以使用
            $receive = Receive::get(["user_id"=>$userId,"coupon_id"=>$couponId,"state"=>0]);
            if (!$receive){
                $this->error("优惠券信息不存在");
            }
            if ($receive['state'] == 1 || $receive['state'] == -1){
                $this->error("优惠券状态不正确");
            }
            //查询优惠券是否在可用时间内
            $coupon = Coupon::get($couponId);
            if (time() < $coupon->start_time || time() > $coupon->end_time){
                $this->error("优惠券已过可用时间");
            }
        }
        if ($couponId > 0){
            //查询优惠券满减金额
            $coupon = Coupon::where("id",$couponId)->field("used_amount")->find();
            $orderAmountTotal = bcmul($goods['price'],$goodsCount,2);
            $endPrice = bcsub($orderAmountTotal,$coupon['used_amount'],2);
        }else{
            $endPrice = bcmul($goods['price'],$goodsCount,2);
        }
        if ($endPrice<0){
            $endPrice=0.0;
        }

        $this->success("成功",["price"=>$endPrice,"data"=>$data]);

    }

    /*
     * 取消订单
     */
    public function cancel(){
        $userId = $this->auth->id;
        $data = $this->request->post();
        $orderNo = $data['orderNo']??"";
        if (empty($orderNo)) {
            $this->error("订单号不能为空");
        }
        $orderInfo = Od::where("order_no",$orderNo)->where("user_id",$userId)->find();
        if (empty($orderInfo)){
            $this->error("订单不存在");
        }
        if ($orderInfo['status']!= 1){
            $this->error("订单状态不正确");
        }
        $orderInfo->status = 5;
        $orderInfo->save();
        if ($orderInfo->order_type == 1){
            //增加库存
            $goods = Goods::where("id",$orderInfo->goods_id)->field("id,stock")->find();
            $res2  = Goods::update(["stock"=>bcsub($goods['stock'],$orderInfo->goods_count)],["id"=>$goods['id']]);
            Log::log("库存更新状态".$res2);
        }elseif ($orderInfo->order_type == 2){
            $json = json_decode(explode("###",$orderInfo->goods_name)[1],true);
            //取消场次预定
            foreach ($json as $val){
                //获取规则
                $rules = Relationship::where(['id'=>$val['areaId']])->value("rule_id");
                $interval = Rule::get($rules);
                foreach ($val['times'] as $v) {
                    //根据间隔时间获取开始和结束时间
                    $startTimes = $v['time'];
                    $str_time = strtotime($v['ynd'] . " " . $v['time']);
                    $end_time = bcadd($str_time, bcmul($interval['interval_time'], 3600));
                    $endTimes = date("H:i", $end_time);
                    // $res3= Reserve::update([
                    //     'user_id'       =>  $orderInfo->user_id,
                    //     "area_id"       =>  $val['areaId'],
                    //     "fixed_date"    =>  $data['fixed_date'],
                    //     "start_times"   =>  $startTimes,
                    //     "end_times"     =>  $endTimes
                    // ]);


                    Reserve::where("order_id",$orderInfo['id'])->update(['order_status'=>1]);
                    //清除redis缓存
                    $key = $orderInfo['venue_id'].'-'.$val['areaId'].'-'.$v['ynd'].'-'.$startTimes.'-'.$endTimes;
                    Cache::rm($key);
                }
            }


            // Log::log("场次更新状态".$res3);
        }elseif ($orderInfo->order_type == 3){
            //取消报名课程
            $res4 = UserLesson::destroy([
                "user_id"       =>  $orderInfo->user_id,
                "lesson_id"     =>  $orderInfo->lesson_id,
            ]);
            Log::log("课程更新状态".$res4);
        }elseif ($orderInfo->order_type == 4){
            //取消活动报名
            $res5 = UserActivity::where("order_id",$orderInfo['id'])->update(['order_status'=>1]);
            Log::log("活动更新状态".$res5);
        }
        //判断是否使用优惠券
        if ($orderInfo->coupon_id > 0){
            //更新优惠券为未使用，判断优惠券是否过期
            $coupon = Coupon::get($orderInfo->coupon_id);
            if (time() > $coupon->end_time){
                $res5 = Receive::update(['state'=>-1],["user_id"=>$orderInfo['user_id'],"coupon_id"=>$orderInfo->coupon_id]);
            }else{
                $res5 = Receive::update(['state'=>0],["user_id"=>$orderInfo['user_id'],"coupon_id"=>$orderInfo->coupon_id]);
            }
            Log::log("优惠券更新状态".$res5);
        }
        $this->success("取消成功");
    }

    /*
     * 创建订单
     */
    public function create(){
        $userId = $this->auth->id;
        $data = $this->request->post();

        $orderType   = $data['orderType']??1;        // 订单类型 1积分订单 2商品订单 3课程订单 4活动订单 5充值订单
        $goodsId     = $data['goodsId']??"";         // 商品ID
        $userName    = $data['userName']??"";        // 用户名
        $mobile      = $data['mobile']??"";          // 用户手机号
        $addressId   = $data['addressId']??"";       // 收货地址ID
        $couponId    = $data['couponId']??0;         // 优惠券ID
        $goodsCount  = $data['goodsCount']??1;       // 商品数量
        $payChannel  = $data['payChannel']??0;       // 支付方式 0积分 1微信 2钱包
        $remark      = $data['remark']??"";          // 订单备注
        $fixedDate   = $data['fixedDate']??"";       // 预定日期
        $venueDetail = $data['venueDetail']??[];     // 预定信息
        $lessonType  = $data['lessonType']??"";      // 课程次数类型
//        $entrants    = $data['entrants']??"";        // 入场人数
        $nameList    = $this->request->post('nameList/a')??"";        // 入场名单
        $condition   = $data['condition']??0;        // 年龄是否超限
        $urgentMobile= $data['urgentMobile']??"";    // 紧急联系人手机号码
        $hd_cc_id   = $data['hd_cc_id']??0;        // 活动场次id

        $info = get_addon_info('epay');
        if(empty($info)){
            $this->error("请先安装微信支付宝整合插件");
        }

        //字段校验
        if (empty($orderType)){
            $this->error("订单类型不能为空");
        }
        if (empty($goodsId)){
            $this->error("商品id不能为空");
        }

        if (!in_array($orderType,[1,2,3,4,5])){
            $this->error("订单类型有误");
        }

        $info = get_addon_info('epay');
        if(empty($info)){
            $this->error("请先安装微信支付宝整合插件");
        }
        $open_id = Detail::get(["user_id"=>$userId]);


        $couponState = 0;
        if ($couponId > 0){
            $couponState = 1;
            if (empty($couponId)){
                $this->error("优惠券信息有误");
            }
            //查看优惠券是否可以使用
            $receive = Receive::get(["user_id"=>$userId,"coupon_id"=>$couponId,"state"=>0]);
            if (!$receive){
                $this->error("优惠券信息不存在");
            }
            if ($receive['state'] == 1 || $receive['state'] == -1){
                $this->error("优惠券状态不正确");
            }
            //查询优惠券是否在可用时间内
            $coupon = Coupon::get($couponId);
            if (time() < $coupon->start_time || time() > $coupon->end_time){
                $this->error("优惠券已过可用时间");
            }
        }
        $venue_id = 0;
        //积分订单
        if ($orderType == 1){
            $integral = $this->auth->score;//用户积分
            //查询商品价格
            $goods = Goods::where("id",$goodsId)->field("id,title,price,stock,daily")->find();

            //判断库存
            if ($goodsCount>$goods['stock']){
                $this->error("库存不足");
            }

            //判断日限购
            $count = Od::where(["user_id"=>$userId,'goods_id'=>$goodsId,"status"=>3])
                    ->where("pay_time",">=",strtotime(date('Y-m-d ').'00:00:00'))
                    ->where("pay_time","<=",strtotime(date('Y-m-d ').'23:59:59'))
                    ->sum("goods_count");
            if (bcadd($count,$goodsCount)>$goods['daily']){
                $this->error("所购买数量超过今日剩余购买数量,今日剩余购买数量:".bcsub($goods['daily'],bcadd($count,$goodsCount)));
            }

            //判断用户积分是否充足
            if ($payChannel == 0){
                if ($couponId > 0){
                    //查询优惠券满减金额
                    $coupon = Coupon::where("id",$couponId)->field("used_amount")->find();
                    $goodsTotal = bcmul($goods['price'],$goodsCount,2);
                    $endPrice = bcsub($goodsTotal,$coupon['used_amount'],2);
                    if ($integral<$endPrice){
                        $this->error("用户可用积分不足");
                    }
                }else{
                    $goodsTotal = bcmul($goods['price'],$goodsCount,2);
                    if ($integral<$goodsTotal){
                        $this->error("用户可用积分不足");
                    }
                }
            }

            //生成订单号
            $orderNo = "JF".venue_orderNo();

        }

        //商品订单
        if ($orderType == 2){
            if (empty($goodsId) || empty($fixedDate)){
                $this->error("商品订单场地信息必填");
            }

            //商品订单 数量默认为1
            $goodsCount = 1;

            //查询该场馆和该场次是否存在
            $venue = Venue::get($goodsId);
            if (empty($venue)){
                $this->error("该场馆信息不存在");
            }
            $venue_id = $venue['id'];

            foreach ($venueDetail as $val){
                $area = Relationship::get(['id'=>$val['areaId'],'venue_id'=>$goodsId]);
                if (empty($area)){
                    $this->error("该场地信息不存在");
                }
                //获取规则
                $rules = Relationship::where(['id'=>$val['areaId']])->value("rule_id");
                $interval = Rule::get($rules);
                foreach ($val['times'] as $v){
                    //校验所选时间是否在时间段内
                    $rule = Rule::where("id",$area['rule_id'])->find();
//                    $yd_times = strtotime($fixedDate.$v['time']);
//                    $rule_times = strtotime($fixedDate.$rule['start_times']);
//                    $rule_timee = strtotime($fixedDate.$rule['end_times']);
//                    if ($yd_times<$rule_times || $yd_times>$rule_timee){
//                        $this->error("所选开始时间段错误");
//                    }
                    //根据间隔时间获取开始和结束时间
                    $startTimes = $v['time'];
                    $str_time = strtotime($fixedDate." ".$v['time']);
                    $end_time = bcadd($str_time,bcmul($interval['interval_time'],3600));
                    $endTimes = date("H:i",$end_time);
                    /*
                    //判断该场次状态
                    $ret = Cache::tag("venue")->get($goodsId.'-'.$val['areaId'].'-'.$fixedDate.'-'.$startTimes.'-'.$endTimes);
                    if ($ret){
                        //判断该时间段是否已被预定
                        $ystimes = strtotime($fixedDate.$startTimes);       //预约的时间（开始）
                        $yetimes = strtotime($fixedDate.$endTimes);         //预约的时间（结束）
                        $times   = explode('-',$ret);
                        $stimes  = strtotime($fixedDate.$times[0]);//场地已被预约的时间（开始）
                        $etimes  = strtotime($fixedDate.$times[1]);  //场地已被预约的时间（结束）
                        if ($ystimes<=$stimes && $ystimes>=$etimes){
                            $this->error("所选场地已被预定");
                        }

                        if ($yetimes>=$stimes && $yetimes<=$etimes){
                            $this->error("所选场地已被预定");
                        }
                    }
                    */
                    $yuding_count = Cache::tag("venue")->get($goodsId.'-'.$val['areaId'].'-'.$fixedDate.'-'.$startTimes.'-'.$endTimes.'_count');
                    if($rule['max_number'] <= $yuding_count){ //如果已报名人数大于最大限制,则提示预定人数已满
                         $this->error("所选场地预定人数已满");
                    }
                    
                }
            }

            //生成订单号
            $orderNo = "SP".venue_orderNo();

        }

        //课程订单
        if ($orderType == 3){
            if (empty($lessonType)){
                $this->error("课程订单相关信息必传");
            }
            //课程订单 数量默认为1
            $goodsCount = 1;

            //判断课程状态
            $lesson = Lesson::get($goodsId);
            if (!$lesson){
                $this->error("课程不存在");
            }
            if ($lesson->state == 0){
                $this->error("课程已禁用");
            }
            $venue_id = $lesson['venue_id'];

            //判断是否已有此活动订单
            $aInfo = Od::where(["user_id"=>$userId,"order_type"=>3,"goods_id"=>$goodsId,"status"=>1])->find();
            if ($aInfo){
                $this->error("你有待支付的课程订单 请先去支付");
            }

            //判断是否已报名
            $res = UserLesson::where(["user_id"=>$userId,"lesson_id"=>$goodsId])->find();
            if ($res){
                $this->error("您已报名，无需重复报名");
            }

            //生成订单号
            $orderNo = "KC".venue_orderNo();
        }

        //活动订单
        if ($orderType == 4){
            //参数校验

            if (empty($nameList)){
                $this->error("入场名单不能为空");
            }
            if (count($nameList)>1){
                $this->error("入场名单最多只能有一人");
            }
//            if (empty($urgentMobile)){
//                $this->error("紧急联系人手机号码不能为空");
//            }
            if (empty($hd_cc_id)){
                $this->error("活动场次id不能为空");
            }

            $goodsCount = 1;


            //判断活动状态
            $activity = Av::get($goodsId);
            if (!$activity || $activity->state == 0){
                $this->error("活动不存在或者状态异常");
            }
            $venue_id = $activity['venue_id'];
            //判断是否已有此活动订单
            $aInfo = Od::where(["user_id"=>$userId,"order_type"=>4,"goods_id"=>$goodsId,"status"=>1])->find();
            if ($aInfo){
                $this->error("你有待支付的活动订单 请先去支付");
            }

            //校验是否在报名时间段内
            $times = explode(" - ",$activity->enrollrange);
            if (time()>=strtotime($times[0])&&time()<=strtotime($times[1])){
                //判断是否已报名
                $info = UserActivity::get(["user_id"=>$userId,"activity_id"=>$activity->id,"order_status"=>0]);
                if (!$info){
                    //查询报名人数是否已满
                    $count_res = Cc::where(['id'=>$hd_cc_id])->find();
                    if ($count_res['y_enroll_num']>=$count_res['enroll_num']){
                        $this->error("报名人数已达上限");
                    }
                }else{
                    $this->error("您已报名过，无需重复报名");
                }
            }else{
                $this->error("已超过可报名时间");
            }

            //生成订单号
            $orderNo = "HD".venue_orderNo();
        }

        //充值订单
        if ($orderType == 5){
            $goods = Recharge::get($goodsId);
            if (!$goods){
                $this->error("充值商品不存在");
            }
            //生成订单号
            $orderNo = "CZ".venue_orderNo();
        }


        //计算实际付款金额
        if ($orderType == 1){
            $goods = Goods::where("id",$goodsId)->field("id,title,price,stock,daily")->find();

        }elseif ($orderType == 2){
            $price = 0;
            foreach ($venueDetail as $v){
                $rule = Relationship::where("id",$v['areaId'])->value("rule_id");
                $details = Rule::get($rule);
                $count = count($v['times']);
                $price = bcadd($price,bcmul($details['price'],$count,2),2);
            }
            $goods['price'] = $price;
        }elseif($orderType == 3){
            $detail = Lesson::get($goodsId);
            $json = json_decode($detail['details_json'],true);
            $price = 0;
            foreach ($json as $v){
                if ($v['type'] == $lessonType){
                    $price = $v['price'];
                }
            }

            $goods['price'] = $price;
        }elseif($orderType == 4){
            $goods['price'] = Cc::where("id",$hd_cc_id)->value("activity_price");
        }elseif ($orderType == 5){
            $goods['price'] = Recharge::where("id",$goodsId)->value("amount");

        }
        if ($couponId > 0){
            //查询优惠券满减金额
            $coupon = Coupon::where("id",$couponId)->field("used_amount")->find();
            $orderAmountTotal = bcmul($goods['price'],$goodsCount,2);
            $endPrice = bcsub($orderAmountTotal,$coupon['used_amount'],2);
        }else{
            $endPrice = bcmul($goods['price'],$goodsCount,2);
        }
        if ($endPrice<0){
            $endPrice=0.01;
        }
        $rand = $code = null;
        if ($orderType != 1 && $orderType != 2 && $orderType != 5){
            $rand = venue_generateRandomString(6);
            $url = "code=".$rand.",orderNo=".$orderNo;
            $img = '/uploads/venue/qr/'.time().rand(0,999);
            //生成二维码图片
            $errorCorrectionLevel = 'L';    //容错级别
            $matrixPointSize = 5;            //生成图片大小
            $img = md5($img).'.png';
            $file_path = ROOT_PATH.config('template.tpl_replace_string.__FILE_UPLOAD_PATH__').'public/uploads/venue/'.'qr/';
            $path = $file_path;
            if(!file_exists($path)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($path,0777,true);
            }
            $filename = $path.$img;
            include_once ROOT_PATH.'addons/venue/library/phpqrcode/phpqrcode.php';
            \QRcode::png($url,$filename , $errorCorrectionLevel, $matrixPointSize, 2);
            $QR = $filename;                //已经生成的原始二维码图片文件
            $QR = imagecreatefromstring(file_get_contents($QR));
            //保存图片,销毁图形，释放内存
            if (!file_exists($filename)) {
                imagepng($QR, $filename);
                imagedestroy($QR);
            } else {
                imagedestroy($QR);
            }
            $code = "/uploads/venue/qr/".$img;
        }
        $data = [
          "order_no"            => $orderNo,                                    //订单号
          "user_id"             => $userId,                                     //用户id
          "goods_id"            => $goodsId,                                    //商品id
          "coupon_id"           => $couponId,                                   //优惠券id
          "status"              => 1,                                           //订单状态
          "goods_count"         => $goodsCount,                                 //商品数量
          "goods_price"         => $goods['price'],                             //商品单价
          "goods_prices"        => bcmul($goods['price'],$goodsCount,2),  //商品总价
          "coupon_state"        => $couponState,                                //是否使用优惠券
          "order_amount_total"  => $endPrice,                                   //实际付款金额
          "pay_channel"         => $payChannel,                                 //支付方式
          "remark"              => $remark,                                     //订单备注
          "createtime"          => time(),                                      //创建时间
          "hd_cc_id"          => $hd_cc_id,                                      //活动场次id
          "venue_id"          => $venue_id,                                      //活动场次id
        ];

        if ($orderType == 1){
            $data['order_type'] = 1;
            $data['address_id'] = $addressId;
            $data['goods_name'] = $goods['title'];
        }elseif ($orderType == 2){
            $data['order_type'] = 2;
            $data['user_name']  = $userName;
            $data['mobile']     = $mobile;
            $data['code'] =  $code;
            $data['goods_name'] = Venue::get($goodsId)['name'] .'###'.json_encode($venueDetail);
            $data['hx_code'] =  $rand;
        }elseif ($orderType == 3){
            $data['order_type'] = 3;
            $data['user_name']  = $userName;
            $data['mobile']     = $mobile;
            $data['goods_name'] = $lesson->title;
            $data['lesson_id']  =  $goodsId;
            $data['lesson_type']=  $lessonType;
            $data['code'] =  $code;
            $data['hx_code'] =  $rand;
        }elseif ($orderType == 4){
            $data['order_type'] = 4;
            $data['activity_id']= $goodsId;
            $data['goods_name'] = Av::get($goodsId)['title'];
            $data['entrants'] = count($nameList);
            $data['name_list'] = json_encode($nameList);
            $data['condition'] = $condition;
            $data['urgent_mobile'] = $urgentMobile;
            $data['code'] =  $code;
            $data['hx_code'] =  $rand;
        }elseif ($orderType == 5){
            $data['order_type'] = 5;
        }

        //数据入库
        Db::startTrans();
        try {
            //插入订单表
            $or = Od::create($data);
            if ($orderType == 2){
                //插入用户订场预定表
                foreach ($venueDetail as $val){
                    if (empty($val)){
                        continue;
                    }
                    $areaId = $val['areaId'];
                    foreach ($val['times'] as $v){
                        $code = mt_rand(1000,9999).$userId.mt_rand(1000,9999);
                        $url = "code=".$code.",orderNo=".$orderNo;
                        $img = '/uploads/venue/qr/'.time().rand(0,999);
                        //生成二维码图片
                        $errorCorrectionLevel = 'L';    //容错级别
                        $matrixPointSize = 5;            //生成图片大小
                        $img = md5($img).'.png';
                        $file_path = ROOT_PATH.config('template.tpl_replace_string.__FILE_UPLOAD_PATH__').'public/uploads/venue/'.'qr/';
                        $path = $file_path;
                        if(!file_exists($path)){
                            //检查是否有该文件夹，如果没有就创建，并给予最高权限
                            mkdir($path,0777,true);
                        }
                        $filename = $path.$img;
                        include_once ROOT_PATH.'addons/venue/library/phpqrcode/phpqrcode.php';
                        \QRcode::png($url,$filename , $errorCorrectionLevel, $matrixPointSize, 2);
                        $QR = $filename;                //已经生成的原始二维码图片文件
                        $QR = imagecreatefromstring(file_get_contents($QR));
                        //保存图片,销毁图形，释放内存
                        if (!file_exists($filename)) {
                            imagepng($QR, $filename);
                            imagedestroy($QR);
                        } else {
                            imagedestroy($QR);
                        }
                        $rand = "/uploads/venue/qr/".$img;

                        //根据间隔时间获取开始和结束时间
                        $startTimes = $v['time'];
                        $str_time = strtotime($fixedDate." ".$v['time']);
                        $end_time = bcadd($str_time,bcmul($interval['interval_time'],3600));
                        $endTimes = date("H:i",$end_time);
                        //计算单场价格
                        $relationship = Relationship::get($areaId);
                        if (!$couponId){
                            $rule = Rule::get($relationship['rule_id']);
                            $goods_price = $rule['price'];
                        }else{
                            $goods_price = $this->getPrice($endPrice,$venueDetail,$areaId);
                        }
                        Reserve::create([
                            "user_id"       =>  $userId,
                            "venue_id"      =>  $goodsId,
                            "area_id"       =>  $areaId,
                            "order_id"      =>  $or->id,
                            "fixed_date"    =>  $fixedDate,
                            "start_times"   =>  $startTimes,
                            "end_times"     =>  $endTimes,
                            "hx_code"       =>  $code,
                            "code"          =>  $rand,
                            "goods_price"   =>  $goods_price,
                            "createtime"    => time(),
                            "updatetime"    => time(),
                        ]);
                        //存入redis
                        $key = $goodsId.'-'.$areaId.'-'.$fixedDate.'-'.$startTimes.'-'.$endTimes;
                        $val = $startTimes.'-'.$endTimes;
                        Cache::tag("venue")->set($key,$val);
                        
                        //预订统计
                        $yuding_count = Cache::tag("venue")->get($key."_count");
                        if(empty($yuding_count)){
                            $yuding_count = 0;
                        }
                        $yuding_count++; // +1
                        Cache::tag("venue")->set($key."_count",$yuding_count);
                        
                    }
                }

                //记录详情
                $reserve = Reserve::where(["order_id"=>$or->id])->field("id,area_id,fixed_date,start_times,end_times,code,hx_code,write,goods_price")->select()->toArray();
                $od = Od::get($or->id);
                Od::update(['goods_name'=>$od['goods_name']."###".json_encode($reserve)],['id'=>$or->id]);
            }elseif ($orderType == 1){
                //减少库存
                Goods::update(["stock"=>bcsub($goods['stock'],$goodsCount)],["id"=>$goods['id']]);
            }

            //更新优惠券为已使用
            if ($couponId){
                Receive::where(["user_id"=>$userId,"coupon_id"=>$couponId])->order("id","asc")->limit(1)->update(["state"=>1]);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error("数据录入失败1：".$e->getMessage().",".$e->getFile().",".$e->getLine());
        }
        //订单放入队列 处理超时取消
        $data = ["orderNo"=>$orderNo];
        if ($orderType == 2){
            $data['venue_id']       = $goodsId;
            $data['fixed_date']     = $fixedDate;
            $data['venueDetail']    = $venueDetail;
        }
        Queue::later( bcmul($this->config['timeout'],60), 'addons\venue\job\Overtime', $data, 'venueOrderQueue');

        $this->success('返回成功',['orderNo'=>$orderNo]);
    }

    public function getPrice($endPrice,$venueDetail,$areaId){
        //调整数据结构
        $detail = [];
        $i = 0;
        $total = 0;
        foreach ($venueDetail as $vv){
            if (empty($vv['times'])){
                continue;
            }else{
                foreach ($vv['times'] as $vt){
                    $detail[$i]['areaId'] = $vv['areaId'];
                    $detail[$i]['price'] = $vt['price'];
                    $i++;
                    $total+=$vt['price'];
                }
            }
        }
        foreach ($detail as $dv){
            if ($dv['areaId']==$areaId){
                return bcdiv(bcmul($dv['price'],$endPrice,2),$total,2);
            }
        }
    }

    /*
     * 获取线下自提地址
     */
    public function address(){
        $this->success("返回成功",["selfdelivery"=>$this->config['selfdelivery']]);
    }

    /*
     * 我的充值订单列表
     */
    public function rechargeList(){
       $user_id = $this->auth->id;
       $page   = $this->request->post('page')??1;  //页码
       $limit  = $this->request->post('limit')??10; //每页显示条数
       $where = ['user_id'=>$user_id,'order_type'=>5];
       $data = Od::where($where)->whereor(["user_id"=>$user_id,"pay_channel"=>2])->where('status','in',[2,3,7])->order("id","desc")
           ->field("id,order_no,goods_id,status,order_amount_total,pay_channel,createtime")
           ->paginate(["page"=>$page,"list_rows"=>$limit])
           ->each(function ($item){
               $item->Recharge = Recharge::get($item->goods_id);
           });
       $this->success('返回成功',$data);
    }

    /*
     * 钱包消费记录
     */
    public function walletList(){
        $user_id = $this->auth->id;
        $page   = $this->request->post('page')??1;  //页码
        $limit  = $this->request->post('limit')??10; //每页显示条数
        $where = ['user_id'=>$user_id];
        $data = Od::where($where)->where('status','in',[2,3,7])->where('pay_channel','2')->order("id","desc")
            ->field("id,order_no,goods_id,status,order_amount_total,createtime")
            ->paginate(["page"=>$page,"list_rows"=>$limit])
            ->each(function ($item){
//                $item->Recharge = Recharge::get($item->goods_id);
            });
        $this->success('返回成功',$data);
    }


    /*
     * 获取订单列表接口
     */
    public function list(){
        $user_id = $this->auth->id;
        $status = $this->request->post('status'); //订单状态 1：待付款 2：待收货 3：已完成 4：待退款 5：已取消 6：已退款
        $order_type = $this->request->post('order_type'); //订单类型
        $page   = $this->request->post('page')??1;  //页码
        $fla   = $this->request->post('flag')??1;  //角色
        $limit  = $this->request->post('limit')??10; //每页显示条数

        $where = [];
        if ($status && $status==2){
            if ($order_type==1){
                if ($status==2){
                    $status=7;
                }
                $where['status'] = ['=',$status];
            }else{
                $where['write'] = ['=',0];
                $where['status'] = ['in',[2,3]];
            }
        }elseif ($status && $status==3){
            if ($order_type==1){
                $where['status'] = ['=',$status];
            }else{
                $where['write'] = ['=',1];
                $where['status'] = ['in',[2,3]];
            }
        }elseif ($status){
            $where['status'] = ['=',$status];
        }
        //查询权限
        if ($fla==2){
            $store = Store::get(["user_id"=>$user_id,"status"=>"normal"]);
            if (!$store){
                $this->error("缺少权限");
            }
            $where['venue_id'] = $store['venue_id'];
        }else{
            $where['user_id'] = ["=",$user_id];
        }


        if($order_type){
            $where['order_type'] = ["=",$order_type];
        }

        $data = Od::where($where)->order("id","desc")
            ->field("id,order_no,order_type,goods_id,goods_name,status,goods_count,goods_price,goods_prices,lesson_type,order_amount_total,pay_channel,code,write,createtime")
            ->paginate(["page"=>$page,"list_rows"=>$limit])
            ->each(function ($item) use($user_id){
                if ($item->code){
                    $item->code = cdnurl($item->code,true);
                }

                if ($item->order_type == 2){
                    $venue = Venue::get($item->goods_id);
                    $item->venue_name = $venue['name'];
                    $item->venue_img = cdnurl($venue['image'],true);
                    $item->venue_address = $venue['address'];

                    $item->times = Reserve::where(["user_id"=>$user_id,"order_id"=>$item->id])->field("start_times,end_times")->select();

                    $reserve = Reserve::where(["user_id"=>$user_id,"order_id"=>$item->id])->field("area_id,fixed_date")->group("area_id")->select();
                    $area = "";
                    if (!empty($reserve->toArray())){
                        foreach ($reserve as $v){
                            $item->fixed_date = $v['fixed_date'];
                            $area      .= Relationship::where("id",$v['area_id'])->value("name").',';
                        }
                        $item->area = substr($area,0,-1);

                    }else{
                        $area_id = json_decode(explode('###',$item->goods_name)[2],true);
                        $areid = array_unique(array_column($area_id,'area_id'));
                        $item->fixed_date = $area_id[0]['fixed_date'];
                        foreach ($areid as $av){
                            $area      .= Relationship::where("id",$av)->value("name").',';
                        }
                        $item->area = substr($area,0,-1);


                    }


                }elseif ($item->order_type == 3){
                    $lesson = Lesson::get($item->goods_id);
                    $item->lesson_name = $lesson['title'];
                    $details = "";

                    $a = json_decode($lesson['details_json'],true);
                    foreach ($a as $v){
                        if ($v['type'] == $item->lesson_type){
                            $details = $v;
                        }
                    }
                    if(isset($details['image'])){
                        $details['image'] = cdnurl($details['image'],true);
                    }
                    $item->details_json = $details;
                }elseif ($item->order_type == 4){
                    $av = Av::get($item->goods_id);
                    $venue = Venue::get($av['venue_id']);
                    $item->venue_name = $venue['name'];
                    $item->venue_img = cdnurl($av['image'],true);
                    $item->hd_name = $av['title'];
                    $type = Type::get(["id"=>$av['type_ids']]);
                    $item->type = $type['venue_type'];
                }elseif ($item->order_type == 1){
                    $goods = Goods::get($item->goods_id);
                    $item->jf_img = cdnurl($goods['thumbnail'],true);
                }
                $item->overtime = bcadd($item->createtime,$this->config['timeout']*60);
            });

        $result = array("total" => $data->total(), "rows" => $data->items());
        $this->success('返回成功',$result);
    }

    /*
     * 获取订单详情接口
     */
    public function detail(){
        $user_id = $this->auth->id;
        $id   = $this->request->post('id');
        if (!$id){
            $this->error("缺少订单id");
        }
        if (!Od::get($id)){
            $this->error("订单不存在");
        }
        $data = Od::where('id',$id)
            ->field("id,order_no,goods_id,order_type,hd_cc_id,goods_name,name_list,status,lesson_type,goods_count,goods_price,goods_prices,order_amount_total,pay_channel,code,hx_code,out_trade_no,remark,code,pay_time,delivery_time,write,createtime,coupon_id,bf_refund,venue_id")
            ->find();
        if ($data['code']){
            $data['code']=cdnurl($data['code'],true);
        }
        if ($data['venue_id']){
            $venue = Venue::get($data['venue_id']);
            $data['venue_lon'] = $venue['lon'];
            $data['venue_lat'] = $venue['lat'];
            $data['venue_address'] = $venue['address'];
        }
        if ($data['order_type'] == 2){
            $detail = Venue::get($data['goods_id']);
            $data['lx_name'] = $detail['lx_name'];
            $data['venue_image'] = cdnurl($detail['image'],true);
            $data['venue_name'] = $detail['name'];
            $data['lx_tel'] = $detail['tel'];
            $data['lon'] = $detail['lon'];
            $data['lat'] = $detail['lat'];
            $data['address'] = $detail['address'];

            $type = Relationship::get(['venue_id'=>$data['goods_id']]);
            $type = Type::get(["id"=>$type['type_id']]);
            $details = Reserve::where(['order_id'=>$data['id']])->select();
            if ($details){
                $details = $details->toArray();
            }
            foreach ($details as &$dv){
                $dv['area_id'] = Relationship::where("id",$dv['area_id'])->value("name");
                $dv['venue_name'] = $detail['name'];
                $dv['lon'] = $detail['lon'];
                $dv['lat'] = $detail['lat'];
                $dv['lat'] = $detail['lat'];
                $dv['type'] = $type['venue_type'];
                $dv['code'] = cdnurl($dv['code'],true);
                //查看是否在退款申请中
                $dv['status'] = $dv['write'];
                $refund_res = Refund::get(['yd_id'=>$dv['id'],'status'=>1]);
                if (isset($refund_res['status']) && $refund_res['status']==1){
                    $dv['refund'] = 2;
                    $dv['status'] = 2;
                }
                $data['fixed_date'] = $dv['fixed_date'];
                //判断是否过期
                $start_time = strtotime($dv['fixed_date']." ".$dv['start_times']);
                if ($start_time < time()){
                    $dv['status'] = 4;
                }
                if ($dv['refund'] == 1){
                    $dv['status'] = 3;
                }

            }
            $data['areaDetail'] = $details;



        }elseif ($data['order_type'] == 4){
            $av = Av::get($data['goods_id']);
            if (!$av){
                $this->error("活动数据已不存在");
            }
            $detail = Venue::get($av['venue_id']);
            $cc = Cc::get($data['hd_cc_id']);
            if ($cc){
                $data['cc_name'] = $cc['title'];
                $data['cc_start_times'] = $cc['start_times'];
                $data['cc_end_times'] = $cc['end_times'];
            }else{
                $data['cc_name'] = "";
                $data['cc_start_times'] = "";
                $data['cc_end_times'] = "";
            }

            $data['lx_name'] = $detail['lx_name'];
            $data['lx_tel'] = $detail['tel'];
            $data['venue_name'] = $detail['name'];
            $data['name_list'] = json_decode($data['name_list'],true);

            $data['hd_name'] = $av['title'];
            $data['hd_image'] = cdnurl($av['image'],true);
            $data['hd_time'] = $av['workrange'];
            $type = Type::get(["id"=>$av['type_ids']]);
            $data['type'] = $type['venue_type'];

        }elseif ($data['order_type'] == 3){
            $lesson = Lesson::get($data['goods_id']);
            $detail = Venue::get($lesson['venue_id']);
            $data['lx_name'] = $detail['lx_name'];
            $data['lx_tel'] = $detail['tel'];
            $data['venue_name'] = $detail['name'];
            $data['address'] = $detail['address'];
            $data['lesson_name'] = $lesson['title'];
            $data['lesson_img']  = cdnurl($lesson['image'],true);
            $details = "";

            $a = json_decode($lesson['details_json'],true);
            foreach ($a as $v){
                if ($v['type'] == $data['lesson_type']){
                    $details = $v;
                }
            }
            $details['image'] = cdnurl($details['image'],true);
            $data['details_json'] = $details;
        }elseif ($data['order_type'] == 1){
            $goods = Goods::get($data['goods_id']);
            $data['jf_img'] = cdnurl($goods['thumbnail'],true);
            $data['selfdeliverys'] = $this->config['selfdeliverys'];

        }
        $data['overtime'] = bcadd($data['createtime'],$this->config['timeout']*60);
        $data['pay_time'] = date("Y-m-d H:i:s",$data['pay_time']);
        $data['createtime'] = date("Y-m-d H:i:s",$data['createtime']);
        if ($data['coupon_id']){
            $data['coupon_price'] = bcsub($data['goods_prices'] ,$data['order_amount_total']);
        }else{
            $data['coupon_price'] = 0;
        }

        $this->success('返回成功',$data);
    }

    /*
     * 发起支付接口
     */
    public function pay(){
        $platform = $this->request->header('platform'); //来源
        $user_id = $this->auth->id;
        $info = get_addon_info('epay');
        if(empty($info)){
            $this->error("请先安装微信支付宝整合插件");
        }
        $detail = Detail::get(["user_id"=>$user_id]);

        $orderNo = $this->request->post('orderNo'); //订单编号
        $payChannel = $this->request->post('payChannel'); //支付方式 0积分 1微信 2钱包
		$openid = $this->request->post('openid'); //订单编号
        if (!$orderNo){
            $this->error("请输入订单编号");
        }
        if ($platform=='mp'){
            $openid = Detail::where("user_id", $this->auth->id)->value("openid");
        }
        
        //判断订单状态
        $order = Od::get(['order_no'=>$orderNo]);
         if ($payChannel){
             $order->pay_channel = $payChannel;
             $order->save();
             $order = Od::get(['order_no'=>$orderNo]);
         }
		if (!$openid && $order['order_type']>1){
            $this->error("请输入openid");
        }

        if (!$order){
            $this->error("订单不存在");
        }
        if ($order['status'] == 5){
            $this->error("该订单已取消，请重新下单");
        }
        if (in_array($order['status'],[2,3,4])){
            $this->error("订单状态不正确");
        }
        //判断订单类型
        if ($order['order_type'] == 1 || $order['pay_channel'] == 2){
            //积分订单 不走微信，扣除用户积分 修改订单状态
            Db::startTrans();
            try {
                if ($order['order_type']==1){
                    //扣除用户积分
//                    $integral = bcsub($this->auth->score,$order['order_amount_total']);
//                    Detail::update(["integral"=>$integral],["user_id"=>$order['user_id']]);
                    \app\common\model\User::score(-$order['order_amount_total'],$order['user_id'],"积分兑换商品");
                    $ms = "预约小程序-积分兑换商品";
                    $zt = "自提地址：".$this->config['selfdeliverys'];
                    //修改订单状态
                    Od::update(["status"=>7,"pay_time"=>time()],['id'=>$order['id']]);
                }else{
                    $user = \app\admin\model\User::get($order['user_id']);
                    if($user['money']<$order['order_amount_total']){
                        throw new \Exception("余额不足");
                    }
                    //扣除用户余额
                    \app\common\model\User::money(-$order['order_amount_total'],$order['user_id'],"支付订单");
                    $ms = "预约小程序-支付订单";
                    $zt = "暂无";
                    //修改订单状态
                    Od::update(["status"=>2,"pay_time"=>time()],['id'=>$order['id']]);
                }




                //异步推送消息
                $message = Message::get(['message_type'=>1]);
                if ($message){

                    $data['openid'] = $openid;
                    $data['masterplate'] = $message->masterplate;
                    if ($data['masterplate']){
                        $data['point'] = 1;//支付成功
                        $json = json_decode($message['multiplejson'],true);
                        //参数名对应订阅消息详细内容参数 （以下为测试）
                        foreach ($json as $jv){
                            switch ($jv['title']) {
                                case '1':
                                    $data['data'][$jv['keyword']]['value'] = $orderNo;
                                    break;
                                case '2':
                                    $data['data'][$jv['keyword']]['value'] = $this->config['lx_name'];
                                    break;
                                case '3':
                                    $data['data'][$jv['keyword']]['value'] = $this->config['lx_tel'];
                                    break;
                                case '4':
                                    $data['data'][$jv['keyword']]['value'] = $ms;
                                    break;
                                case '5':
                                    $data['data'][$jv['keyword']]['value'] = $zt;
                                    break;
                                default:
                                    $data['data'][$jv['keyword']]['value'] = "测试";

                            }
                        }
                        Queue::later( 2, 'addons\venue\job\SendMessage', $data, 'venueOrderQueue');
                    }

                }


                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error("支付失败：".$e->getMessage());
            }
            $this->success('支付成功',['orderNo'=>$order['order_no']]);

        }else{
            //活动订单金额为0的订单
            if (($order['order_type'] == 4 || $order['order_type'] == 2) && $order['goods_price'] == 0){
                //修改订单状态
                Od::update(["status"=>2,"pay_time"=>time()],['id'=>$order['id']]);
                UserActivity::create([
                    "user_id"       =>  $order['user_id'],
                    "activity_id"   =>  $order['activity_id'],
                    "activity_price"=>  $order['goods_price'],
                    "entrants"      =>  $order['entrants'],
                    "name_list"     =>  $order['name_list'],
                    "condition"     =>  $order['condition'],
                    "urgent_mobile" =>  $order['urgent_mobile'],
                    "createtime"    => time()
                ]);
                $this->success('免费活动支付成功',[],0);
            }
            //调用微信支付
            if ($order['order_type']==2){
                $pay_title = "预订场馆";
            }elseif ($order['order_type']==3){
                $pay_title = "购买课程";
            }elseif ($order['order_type']==3){
                $pay_title = "报名活动";
            }else{
                $pay_title = "充值";
            }
            $params = [
                'amount'    =>  $order['order_amount_total'],
                'orderid'   =>  $order['order_no'],
                'type'      =>  "wechat",
                'title'     =>  $pay_title,
                'notifyurl' =>  request()->domain()."/addons/venue/order/notifyx/type/wechat",
                'returnurl' =>  "",
                'method'    =>  $platform,
                'openid'    =>  $openid,
            ];
            $result = Service::submitOrder($params);
            $this->success('成功',$result);
        }
    }


    /**
     * 支付成功回调
     */
    public function notifyx()
    {
        $type = $this->request->param('type');
        $pay = \addons\epay\library\Service::checkNotify($type);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();

        //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
        if ($data['result_code'] == "SUCCESS"){
            $order   = Od::get(["order_no"=>$data['out_trade_no']]);
            if (!$order){
                return $pay->success()->send();
            }
            if ($order['status'] > 1){
                return $pay->success()->send();
            }

            $status = 2;
            if ($order['order_type']==5){
                $status = 3;
            }
            Od::update(["status"=>$status,'pay_channel'=>1,'out_trade_no'=>$data['transaction_id'],"pay_time"=>time()],["order_no"=>$data['out_trade_no']]);
            //判断订单类型
            if ($order['order_type'] == 3){
                //插入用户课程关联表
                UserLesson::create([
                    "user_id"       =>  $order['user_id'],
                    "lesson_id"     =>  $order['lesson_id'],
                    "createtime"    =>  time(),
                ]);
            }elseif ($order['order_type'] == 4){
                //插入用户活动报名表
                UserActivity::create([
                    "order_id"       =>  $order['id'],
                    "user_id"       =>  $order['user_id'],
                    "activity_id"   =>  $order['activity_id'],
                    "activity_price"=>  $order['goods_price'],
                    "entrants"      =>  $order['entrants'],
                    "name_list"     =>  $order['name_list'],
                    "condition"     =>  $order['condition'],
                    "urgent_mobile" =>  $order['urgent_mobile'],
                    "createtime"    => time()
                ]);
                Cc::where(["id"=>$order['hd_cc_id']])->update(["y_enroll_num"=>Db::raw("y_enroll_num+1")]);
            }elseif ($order['order_type'] == 5){
                //增加用户余额
                $recharge = Recharge::get(['id'=>$order['goods_id']]);
                \app\common\model\User::money($recharge['amount_over'],$order['user_id'],"充值");
            }

            //赠送积分
            if (in_array($order->order_type,[2,3,4,5])){
                //积分订单不参与赠送积分
                switch ($order->order_type){
                    case 2:
                        $points = \app\admin\model\venue\Venue::get($order->goods_id)->reward_points;
                        $memo = "预订场馆赠送";
                        break;
                    case 3:
                        $detail = Lesson::get($order->goods_id)->details_json;
                        $a = json_decode($detail,true);
                        foreach ($a as $v){
                            if ($v['type'] == $order->lesson_type){
                                $points = $v['points'];
                            }
                        }
                        $memo = "购买课程赠送";
                        break;
                    case 4:
                        $points = \app\admin\model\venue\activity\Activity::get($order->activity_id)->reward_points;
                        $memo = "报名活动赠送";
                        break;
                    case 5:
                        $points = 0;
                        $memo = "充值赠送";
                        break;
                    default:
                        $points = 0;
                        $memo = "";

                }
                if ($points == 0){
                    //取系统默认赠送积分数
                    $points = $this->config['default_points'];
                }
                \app\common\model\User::score($points,$order->user_id,$memo);

            }

            //添加余额明细
            if ($order->order_amount_total>0){
                if ($order->venue_id){
                    $venue = Venue::get($order->venue_id);
                    $money = $order->order_amount_total+$venue['money'];
                    Balance::create([
                        "type"=>1,
                        "order_no"=>$order->order_no,
                        "money"=>$order->order_amount_total,
                        "balance"=>$money,
                        "user_id"=>$order['user_id'],
                        "venue_id"=>$order['venue_id'],
                        "createtime"=>time(),
                        "updatetime"=>time(),
                    ]);
                    $venue->money = $money;
                    $venue->save();
                }



            }


            //异步推送消息
            $message = Message::get(['message_type'=>1]);
            if (isset($message) && $message['multiplejson']){
                Log::info("进入支付回调消息推送流程");
                switch ($order['order_type']){
                    case 2;
                        $venue = Venue::get($order->goods_id);
                        $lx_name = $venue['lx_name'];
                        $lx_mobile = $venue['tel'];
                        $md_name = $venue['name'];
                        $desc = Reserve::where("order_id",$order->id)->select();
                        $time = "";
                        $area_name = "";
                        foreach ($desc as $k => $v){
                            $time = $v['fixed_date'];
//                            $area = Relationship::get($v['area_id']);
//                            $area_name .= "场馆名称：".$area['name']." 开始时间：".$v['start_times']." 结束时间：".$v['end_times'].'|';
                        }
//                        $notes = "预约日期:".$time.substr($area_name,0,-1);
                        $notes = "预约日期:".$time;
                        break;
                    case 3;
                        $lesson = Lesson::get($order->goods_id);
                        $venue = Venue::get($lesson['venue_id']);
                        $lx_name = $venue['lx_name'];
                        $lx_mobile = $venue['tel'];
                        $md_name = $venue['name'];
                        $notes = '开课时间：'.$lesson['workrange'];
                        break;
                    case 4;
                        $lesson = \app\admin\model\venue\activity\Activity::get($order->goods_id);
                        $venue = Venue::get($lesson['venue_id']);
                        $lx_name = $venue['lx_name'];
                        $lx_mobile = $venue['tel'];
                        $md_name = $venue['name'];
                        $notes = '活动时间：'.$lesson['workrange'];
                        break;
                    default:
                        $lx_name = "暂无";
                        $lx_mobile = "暂无";
                        $md_name = "暂无";
                        $notes = "充值订单";
                }
                $json = json_decode($message['multiplejson'],true);
                //参数名对应订阅消息详细内容参数 （以下为测试）
                $data = [];
                foreach ($json as $jv){
                    switch ($jv['title']) {
                        case '1':
                            $data['data'][$jv['keyword']]['value'] = intval($order->out_trade_no);
                            break;
                        case '2':
                            $data['data'][$jv['keyword']]['value'] = empty($lx_name)?"暂无":$lx_name;
                            break;
                        case '3':
                            $data['data'][$jv['keyword']]['value'] = intval($lx_mobile);
                            break;
                        case '4':
                            $data['data'][$jv['keyword']]['value'] = empty($md_name)?"暂无":$md_name;
                            break;
                        case '5':
                            $data['data'][$jv['keyword']]['value'] = $notes;
                            break;

                    }
                }
                $data['openid'] = Detail::where("user_id", $order->user_id)->value("openid");
                $data['masterplate'] = $message->masterplate;
                $data['point'] = 1;//支付成功
                Log::info("推送用户openid:".$data['openid']);
                Log::info("推送数据:".json_encode($data));
                Log::info("进入支付回调消息推送队列");
                Queue::later( 2, 'addons\venue\job\SendMessage', $data, 'venueOrderQueue');
            }

        }else{
            Od::update(["status"=>1],["order_no"=>$data['out_trade_no']]);
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }

    /*
     * 订单核销
     */
    public function write(){
        $code = $this->request->post("code");
        if (!$code){
            $this->error("缺少核销码");
        }
        //查询该核销码是否存在
        $order = Od::get(['hx_code'=>$code]);
        if (!$order){
            $reserve = Reserve::get(['hx_code'=>$code]);
            if (!$reserve){
                $this->error("核销码不存在");
            }
            if ($reserve['write'] == 1){
                $this->error("该订单已核销");
            }
            $order = Od::get(['id'=>$reserve['order_id']]);
            if ($order['status'] == 4 || $order['drawback_no'] != ""){
                $this->error("该订单状态不正确");
            }
            Reserve::update(['write'=>1],['hx_code'=>$code]);
        }
        if ($order['write'] == 1){
            $this->error("该订单已核销");
        }
        if ($order['status'] == 4 || $order['drawback_no'] != ""){
            $this->error("该订单状态不正确");
        }
        Od::update(['write'=>1],['hx_code'=>$code]);
        $this->success("核销成功");
    }

    /*
      * 退款申请
      */
    public function refund(){
        $id = $this->request->post('id'); //订单id
        $yd_id = $this->request->post('yd_id'); //预订场次id
        $desc = $this->request->post('desc')??""; //退款理由
//        if (!$desc){
//            $this->error("退款理由不能为空");
//        }
        $user_id = $this->auth->id;
        $order = Od::get($id);
        if (!$order){
            $this->error("不存在此订单");
        }
        if ($order['status'] != 3 && $order['status'] != 2 && $order['status'] != 4){
            $this->error("订单状态不正确");
        }
        if (!$yd_id){
            $refund = Refund::get(["order_id"=>$id,"status"=>1]);
            if ($refund){
                $this->error("该订单已申请退款,无需再申请");
            }
        }

        //判断订单类型
        if ($order['order_type'] == 2){
            //查询预定的时间
            $reserve = Reserve::where("order_id",$id)->group("fixed_date")->find();
            if (time()-strtotime($reserve['fixed_date']." 00:00:00")>86400){
                $this->error("已过退款时间");
            }
        }
        Od::update(["status"=>4,'updatetime'=>time()],["id"=>$id]);
        if ($yd_id){
            $money = Reserve::get($yd_id)['goods_price'];
        }else{
            $money = $order['order_amount_total'];
        }
        //判断是否退款自动审核
        if ($this->config['refund_switch']){
            $refundNo = "TK".venue_orderNo();
            //判断用户是钱包支付还是微信支付
            if ($order['pay_channel']==2){
                //钱包支付退款
                \app\common\model\User::money($money,$order['user_id'],"退款");
                //修改余额明细
                $venue = Venue::get($order->venue_id);
                $z_money = $venue['money'] - $money;

                Balance::create([
                    "type"=>2,
                    "order_no"=>$refundNo,
                    "money"=>$money,
                    "balance"=>$z_money,
                    "user_id"=>$order->user_id,
                    "venue_id"=>$order->venue_id,
                    "createtime"=>time(),
                    "updatetime"=>time(),
                ]);
                $venue->money = $z_money;
                $venue->save();
                if (!$yd_id){
                    Reserve::update(["refund"=>1,"is_cl"=>1,"refund_no"=>$refundNo,"order_status"=>1],["order_id"=>$id]);
                }else{
                    $reserve = Reserve::get($yd_id);
                    $reserve->refund = 1;
                    $reserve->is_cl = 1;
                    $reserve->order_status = 1;
                    $reserve->refund_no = $refundNo;
                    $reserve->save();
                }

                //添加退款记录
                Refund::create([
                    "user_id"=>$user_id,
                    "order_id"=>$id,
                    "refund_money"=>$money,
                    "refund_no"=>$refundNo,
                    "refund_desc"=>$desc,
                    "yd_id"=>$yd_id,
                    "status"=>4,
                    "createtime"=>time(),
                ]);
                //查询该订单下 所有场地是否已处理
                $reserve_res = Reserve::where(['order_id'=>$order['id'],"is_cl"=>0])->find();
                if (!$reserve_res){
                    $order->status = 5;
                }
                $count = Reserve::where(['order_id'=>$order['id']])->count();
                if ($count>1){
                    $order->bf_refund = 1;
                }
                $order->save();

                $this->success("退款成功");

            }else{
//            try {
                //生成退款单号 查询订单
                if ($order['order_type']!=2 || $yd_id==0){
                    
                    if($money > 0){ //退款金额大于 0 
                        $orderd['transaction_id'] = $order['out_trade_no'];
                        $orderd['out_refund_no'] = $refundNo;
                        $orderd['total_fee'] = bcmul($order['order_amount_total'], 100, 0); // 原支付交易的订单总金额
                        $orderd['refund_fee'] = bcmul($money, 100, 0); // 退款金额
                        $orderd['notify_url'] = "";
                        $config = Service::getConfig();
                        $pay = Pay::wechat($config);
                        $result = $pay->refund($orderd);
                    }else{
                        $result = ['return_code'=>"SUCCESS"];
                    }
                    if ($result['return_code']=="SUCCESS"){
                        //修改余额明细
                        $venue = Venue::get($order->venue_id);
                        $money = $venue['money'] - $order->order_amount_total;

                        Balance::create([
                            "type"=>2,
                            "order_no"=>$refundNo,
                            "money"=>$order->order_amount_total,
                            "balance"=>$money,
                            "user_id"=>$order['user_id'],
                            "venue_id"=>$order['venue_id'],
                            "createtime"=>time(),
                            "updatetime"=>time(),
                        ]);
                        $venue->money = $money;
                        $venue->save();
                        $order->status = 5;
                        $order->save();
                        //添加退款记录
                        Refund::create([
                            "user_id"=>$user_id,
                            "order_id"=>$id,
                            "refund_money"=>$money,
                            "refund_no"=>$refundNo,
                            "refund_desc"=>$desc,
                            "yd_id"=>$yd_id,
                            "status"=>4,
                            "createtime"=>time(),
                        ]);
                        Reserve::update(["refund"=>1,"is_cl"=>1,"refund_no"=>$refundNo,"order_status"=>1],["order_id"=>$id]);


                        if ($order['order_type']==3){
                            UserLesson::where(['user_id'=>$order['user_id'],'lesson_id'=>$order['lesson_id']])->delete();
                        }
                        if ($order['order_type']==4){
                            UserActivity::where(['user_id'=>$order['user_id'],'activity_id'=>$order['activity_id']])->delete();
                            Cc::where(['id'=>$order['hd_cc_id']])->update(['y_enroll_num'=>Db::raw("y_enroll_num-1")]);
                        }


                        $this->success("退款成功");
                    }else{
                        $this->error("退款失败");
                    }

                }else{
                    
                    //单场次退款
                    $reserve = Reserve::get($yd_id);
                    if ($reserve['write']==1){
                        $this->error("该场次已核销");
                    }
                    
                    if($money > 0){ //退款金额大于 0 
                        $orderd['transaction_id'] = $order['out_trade_no'];
                        $orderd['out_refund_no'] = $refundNo;
                        $orderd['total_fee'] = bcmul($order['order_amount_total'], 100, 0); // 原支付交易的订单总金额
                        $orderd['refund_fee'] = bcmul($money, 100, 0); // 退款金额
                        $orderd['notify_url'] = "";
                        $config = Service::getConfig();
                        $pay = Pay::wechat($config);
                        $result = $pay->refund($orderd);
                    }else{
                        $result = ['return_code'=>"SUCCESS"];
                    }
                    
                    if ($result['return_code']=="SUCCESS"){
                        //修改余额明细
                        $venue = Venue::get($order->venue_id);
                        $money = $venue['money'] - $reserve['goods_price'];

                        Balance::create([
                            "type"=>2,
                            "order_no"=>$refundNo,
                            "money"=>$reserve['goods_price'],
                            "balance"=>$money,
                            "user_id"=>$order->user_id,
                            "venue_id"=>$order->venue_id,
                            "createtime"=>time(),
                            "updatetime"=>time(),
                        ]);
                        $venue->money = $money;
                        $venue->save();
                        $reserve->refund = 1;
                        $reserve->order_status = 1;
                        $reserve->is_cl = 1;
                        $reserve->refund_no = $refundNo;
                        $reserve->save();
                        //添加退款记录
                        Refund::create([
                            "user_id"=>$user_id,
                            "order_id"=>$id,
                            "refund_money"=>$money,
                            "refund_no"=>$refundNo,
                            "refund_desc"=>$desc,
                            "yd_id"=>$yd_id,
                            "status"=>4,
                            "createtime"=>time(),
                        ]);
                        //查询该订单下 所有场地是否已处理
                        $reserve_res = Reserve::where(['order_id'=>$order['id'],"is_cl"=>0])->find();
                        if (!$reserve_res){
                            $order->status = 5;
                        }
                        $count = Reserve::where(['order_id'=>$order['id']])->count();
                        if ($count>1){
                            $order->bf_refund = 1;
                        }
                        $order->save();

                        $this->success("退款成功");
                    }else{
                        $this->success("退款失败");
                    }
                }
            }
//            }catch (\Exception $e){
//                Log::error($e->getMessage());
////                $this->error($e->getMessage());
//            }



        }else{
            //添加退款记录
            Refund::create([
                "user_id"=>$user_id,
                "order_id"=>$id,
                "refund_money"=>$money,
                "refund_desc"=>$desc,
                "yd_id"=>$yd_id,
                "createtime"=>time(),
            ]);
            $this->success("申请成功");
        }


    }

    /**
     * 获取所有家属
     */
    public function getFamilyList(){
        $user_id = $this->auth->id;
        dump($user_id);die;
        $family = Db::name('user')->where('pid',$user_id)->select();
        $this->success("获取成功",$family);
    }

}
